package cn.yto.wdgj.wdgjgptdigitaltool.service.impl;

import cn.yto.base.page.BasePage;
import cn.yto.response.BaseResponse;
import cn.yto.response.DataResult;
import cn.yto.utils.BeanUtil;
import cn.yto.utils.JsonUtil;
import cn.yto.utils.StringUtil;
import cn.yto.wdgj.common.reponse.MutiResponse;
import cn.yto.wdgj.wdgjgptdigitaltool.entity.dto.request.GptCaseMaintenanceRequest;
import cn.yto.wdgj.wdgjgptdigitaltool.entity.dto.response.GptCaseMaintenanceResponse;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.gpt.GptCaseMaintenanceMapper;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.po.GptCaseMaintenance;
import cn.yto.wdgj.wdgjgptdigitaltool.service.GptCaseMaintenanceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GptCaseMaintenanceServiceImpl implements GptCaseMaintenanceService {

    @Autowired
    private GptCaseMaintenanceMapper gptCaseMaintenanceMapper;

    @Override
    public DataResult<MutiResponse<GptCaseMaintenanceResponse>> getAllGptCaseMaintenance(GptCaseMaintenanceRequest gptCaseMaintenanceRequest) {
        StringBuilder logBuilder = new StringBuilder("【根据条件获取列表】paramData request=[ " + JsonUtil.toJson(gptCaseMaintenanceRequest) + " ]，");
        LambdaQueryWrapper<GptCaseMaintenance> lambdaQueryWrapper = new LambdaQueryWrapper<GptCaseMaintenance>();
        if (gptCaseMaintenanceRequest.getId() != null) {
            lambdaQueryWrapper.in(GptCaseMaintenance::getId, gptCaseMaintenanceRequest.getId());
        }
        if (StringUtil.isNotBlank(gptCaseMaintenanceRequest.getTag())) {
            lambdaQueryWrapper.in(GptCaseMaintenance::getTag, gptCaseMaintenanceRequest.getTag());
        }
        if (StringUtil.isNotBlank(gptCaseMaintenanceRequest.getIntentName())) {
            lambdaQueryWrapper.in(GptCaseMaintenance::getIntentName, gptCaseMaintenanceRequest.getIntentName());
        }
        if (StringUtil.isNotBlank(gptCaseMaintenanceRequest.getMatcherContent())) {
            lambdaQueryWrapper.like(GptCaseMaintenance::getMatcherContent, gptCaseMaintenanceRequest.getMatcherContent());
        }

        BasePage page = new BasePage();
        page.setCurrentPage(gptCaseMaintenanceRequest.getPageNo());
        page.setPageSize(gptCaseMaintenanceRequest.getPageSize());
        page.setQueryCount(true);

        Page<GptCaseMaintenance> pageResult = PageHelper.startPage(page.getCurrentPage(),
                page.getPageSize(), page.getQueryCount()).doSelectPage(() -> gptCaseMaintenanceMapper.selectList(lambdaQueryWrapper));

        int resultNum = CollectionUtils.isEmpty(pageResult.getResult()) ? 0 : pageResult.getResult().size();
        logBuilder.append("接口查询数据量= [ ").append(resultNum).append(" ]，");

        MutiResponse<GptCaseMaintenanceResponse> pageResponse = new MutiResponse<>();
        List<GptCaseMaintenanceResponse> myWorkOrderResponses = BeanUtil.copyByList(pageResult.getResult(), GptCaseMaintenanceResponse.class);

        pageResponse.setItems(myWorkOrderResponses);
        pageResponse.setPageNo(gptCaseMaintenanceRequest.getPageNo());
        if (CollectionUtils.isNotEmpty(pageResult.getResult())) {
            pageResponse.setLimit(pageResult.getResult().size());
        } else {
            pageResponse.setLimit(0);
        }
        if (pageResponse.getLimit() < gptCaseMaintenanceRequest.getPageSize()) {
            // 查询出来的接口比分页参数少，则认为没有更多数据了
            pageResponse.setMorePage(false);
        } else {
            pageResponse.setMorePage((long) page.getCurrentPage() * page.getPageSize() < pageResult.getTotal());
        }
        pageResponse.setTotal(pageResult.getTotal());
        log.info(logBuilder.toString());
        return DataResult.ok(pageResponse);
    }

    @Override
    public DataResult<BaseResponse> delGptCaseMaintenance(Long caseId) {
        StringBuilder logBuilder = new StringBuilder("【根据条件删除数据】caseId request=[ " + caseId + " ]，");
        try {
            int i = gptCaseMaintenanceMapper.deleteById(caseId);
            if (i > 0) {
                logBuilder.append("删除成功");
                return DataResult.ok();
            }
            logBuilder.append("删除失败");
        } catch (Exception e) {
            log.error("【根据条件删除数据】caseId：{} 删除失败", caseId, e);
            logBuilder.append("删除失败");
        } finally {
            log.info(logBuilder.toString());
        }
        return DataResult.fail("删除失败");
    }

    @Override
    public DataResult<BaseResponse> updateGptCaseMaintenance(GptCaseMaintenanceRequest request) {
        StringBuilder logBuilder = new StringBuilder("【根据条件更新数据】request=[ " + JsonUtil.toJson(request) + " ]，");
        GptCaseMaintenance gptCaseMaintenance = new GptCaseMaintenance();
        BeanUtils.copyProperties(request, gptCaseMaintenance);
        try {
            gptCaseMaintenance.setUpdateTime(new Date());
            int i = gptCaseMaintenanceMapper.updateById(gptCaseMaintenance);
            if (i > 0) {
                logBuilder.append("更新成功");
                return DataResult.ok();
            }
            logBuilder.append("更新失败");
        } catch (Exception e) {
            log.error("【根据条件更新数据】request：{} 更新失败", JsonUtil.toJson(request), e);
            logBuilder.append("更新失败");
        } finally {
            log.info(logBuilder.toString());
        }
        return DataResult.fail("更新失败");
    }

    @Override
    public DataResult<BaseResponse> saveGptCaseMaintenance(GptCaseMaintenanceRequest request) {
        StringBuilder logBuilder = new StringBuilder("【根据条件保存数据】request=[ " + JsonUtil.toJson(request) + " ]，");
        GptCaseMaintenance gptCaseMaintenance = new GptCaseMaintenance();
        BeanUtils.copyProperties(request, gptCaseMaintenance);
        try {
            gptCaseMaintenance.setCreateTime(new Date());
            int insert = gptCaseMaintenanceMapper.insert(gptCaseMaintenance);
            if (insert > 0) {
                logBuilder.append("保存成功");
                return DataResult.ok();
            }
            logBuilder.append("保存失败");
        } catch (Exception e) {
            log.error("【根据条件保存数据】request：{} 保存失败", JsonUtil.toJson(request), e);
            logBuilder.append("保存失败");
        } finally {
            log.info(logBuilder.toString());
        }
        return DataResult.fail("保存失败");
    }
}
